<template>
	<a-spin :spinning="spinning" :delay="120">
		<div class="container">
			<div class="toolbar">
				<a-form ref="formRef" :model="list">
					<h3 style="margin: 10px 0; text-align: center"><b>{{ (contract?.project?.name || '') + ' ' + applyArgs.contract_name + '结算单' }}</b></h3>
					<a-table :columns="innerColumns" :scroll="tableScroll" row-key="id" children-column-name="children" :pagination="false" :data-source="list" :loading="loading">
						<template #headerCell="{ column }">
							<template v-if="column.title.includes('\n')">
								<span>
									{{ column.title.split('\n')[0] }}<br />{{ column.title.split('\n')[1] }}
								</span>
							</template>
							<template v-else-if="column.title === 'up_per'">
								<span v-if="contract.price_type === 2">
									浮动比率±(%)
								</span>
								<span v-else-if="contract.price_type === 3">
									浮动价格(±)
								</span>
							</template>
						</template>
						<template #bodyCell="{ column, index, record }">
							<template v-if="column.dataIndex === 'append_subprice'">
								<a-form-item :name="[index, 'append_subprice']" :rules="{ required: true, message: '请输入' }">
									<a-input-number v-model:value="record.append_subprice" placeholder="请输入" :disabled="optDisabled" />
								</a-form-item>
							</template>
							<template v-else-if="column.dataIndex === 'use_position' && [1,2,3,5].includes(list[0]?.settlement.ys_type)">
								<a-row :gutter="20">
									<a-col :span="24">
										<a-form-item :name="[index, 'use_position']" :rules="{ required: true, message: '请选择详细部位' }">
											<a-tree-select v-model:value="record.use_position" :dropdown-match-select-width="false" :show-search="true" placeholder="请选择详细部位" allow-clear tree-default-expand-all :tree-data="gonghaoTree" tree-node-filter-prop="label" style="width:100%" :disabled="optDisabled" @change="changeUsePosition(record)">
												<template #title="{ label }">{{ label }}</template>
											</a-tree-select>
										</a-form-item>
									</a-col>
								</a-row>
							</template>
							<template v-else-if="column.dataIndex === 'account_type_id'">
								<a-row :gutter="20">
									<a-col :span="24">
										<a-form-item :name="[index, 'account_type_id']" :rules="{ required: true, message: '核算分类' }">
											<a-select v-model:value="record.account_type_id" placeholder="请选择核算分类" :options="accountTypeOptions" option-filter-prop="label" :disabled="optDisabled"></a-select>
										</a-form-item>
									</a-col>
								</a-row>
							</template>
							<template v-else-if="column.dataIndex === 'expenditure_id'">
								<a-row :gutter="20">
									<a-col :span="24">
										<a-form-item :name="[index, 'expenditure_id']" :rules="{ required: true, message: '支出方向' }">
											<a-select v-model:value="record.expenditure_id" placeholder="请选择支出方向" :options="expenditureOptions" option-filter-prop="label" :disabled="optDisabled" allow-clear></a-select>
										</a-form-item>
									</a-col>
								</a-row>
							</template>
							<template v-else-if="column.dataIndex === 'brand'">
								<a-row :gutter="20">
									<a-col :span="24">
										<a-form-item :name="[index, 'brand']" :rules="{ required: true, message: '请输入品牌' }" :disabled="optDisabled">
											<a-input v-model:value="record.brand" placeholder="请输入品牌" :disabled="optDisabled" />
										</a-form-item>
									</a-col>
								</a-row>
							</template>
						</template>
						<template #summary>
							<a-table-summary-row style="background-color:#f0f0f0;font-size:12px;font-weight:bold;">
								<a-table-summary-cell :col-span="3" style="text-align: center">
									<a-typography-text type="danger">合计</a-typography-text>
								</a-table-summary-cell>
								<a-table-summary-cell v-if="list[0]?.settlement.ys_type === 2" :col-span="3"></a-table-summary-cell>
								<!--								<a-table-summary-cell :col-span="11"></a-table-summary-cell>-->
								<a-table-summary-cell :col-span="8"></a-table-summary-cell>
								<a-table-summary-cell :col-span="1" style="text-align: center">{{ totalAmount.append_subprice }}</a-table-summary-cell>
								<a-table-summary-cell v-if="contract.price_type !== 1 && contract.price_type" :col-span="1" style="text-align: center">
									{{ contract.price_type ===3? totalAmount.up_per: '' }}
								</a-table-summary-cell>
								<a-table-summary-cell :col-span="1" style="text-align: center">{{ totalAmount.with_tax_subprice }}</a-table-summary-cell>
								<a-table-summary-cell :col-span="1" style="text-align: center">{{ totalAmount.with_tax_amount }}</a-table-summary-cell>
								<a-table-summary-cell :col-span="1" style="text-align: center">{{ totalAmount.without_tax_subprice }}</a-table-summary-cell>
								<a-table-summary-cell :col-span="1" style="text-align: center">{{ totalAmount.without_tax_amount }}</a-table-summary-cell>
								<a-table-summary-cell :col-span="1" style="text-align: center">{{ totalAmount.tax_amount }}</a-table-summary-cell>
								<a-table-summary-cell :col-span="2">
									<a-input-number v-model:value="totalAmount.amount" :min="0" addon-before="本次结算总额" placeholder="请输入金额" :disabled="optDisabled" />
								</a-table-summary-cell>
							</a-table-summary-row>
						</template>
					</a-table>
				</a-form>
				<div>
					<h3 style="margin: 10px 0;"><b>单据信息</b></h3>
					<a-form ref="formOther" :model="applyArgs">
						<a-descriptions bordered size="middle">
							<a-descriptions-item label="合同号">{{ applyArgs.contract_name }}</a-descriptions-item>
							<a-descriptions-item label="供应商" :span="2">{{ applyArgs.supplier_name }}</a-descriptions-item>
							<a-descriptions-item label="结算附件下载">
								<!--								<a-button :href="list[0]?.settlement.file_path[0]?.url" target="_blank">下载附件</a-button><br />-->
								<!--								<span style="color:#ccc">{{ list[0]?.settlement.file_path[0]?.name }}</span>-->
								<a :href="list[0]?.settlement.file_path[0]?.url" target="_blank">{{ list[0]?.settlement.file_path[0]?.name }}</a>
							</a-descriptions-item>
							<a-descriptions-item label="合同附件" :span="2">
								<a :href="applyArgs.contract_file?.url" target="_blank">{{ applyArgs.contract_file?.name }}</a>
							</a-descriptions-item>
							<a-descriptions-item label="结算说明" :span="3">
								{{ applyArgs.memo }}
							</a-descriptions-item>
						</a-descriptions>
					</a-form>
					<div class="text-center mt-5">
						<div>
							<a-button type="primary" @click="agree()">通过</a-button>
							<a-button type="default" style="margin-left: 1rem" @click="revocation()">撤回</a-button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</a-spin>
</template>
<script setup>
import { useRoute, useRouter } from "vue-router";
import { computed, getCurrentInstance, onMounted, ref } from "vue";
import { post, treeToList } from "@/utils/index.js";
import dayjs from "dayjs";
import { Modal } from "ant-design-vue";
const settleStatelist = [
	{ value: 1, label: "结算中" },
	{ value: 2, label: "已结算" },
	{ value: 3, label: "未知" }
];
const columns = [
	{
		title: "申请时间",
		dataIndex: "settlement",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return dayjs(text.apply_time).format("YYYY-MM-DD HH:mm:ss");
		}
	},
	{
		title: "状态",
		dataIndex: "settlement",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return settleStatelist.filter(item => item.value === text.status)[0].label;
		}
	},
	{
		title: "材料名称",
		dataIndex: "material",
		sorter: false,
		width: 150,
		ellipsis: true,
		customRender: ({ text, record, index, column }) => {
			return text.name;
		}
	},
	{
		title: "规格型号",
		dataIndex: "model",
		sorter: false,
		width: 150,
		ellipsis: true,
	},
	{
		title: "计量单位",
		dataIndex: "unit",
		sorter: false,
		width: 150,
		ellipsis: true,
	},
	{
		title: "采购数量",
		dataIndex: "quantity",
		sorter: false,
		width: 150,
		ellipsis: true,
	},
	{
		title: "验收数量",
		dataIndex: "ys_quantity",
		sorter: false,
		width: 150,
		ellipsis: true,
	},
	{
		title: "发货单编号",
		dataIndex: "real_code",
		sorter: false,
		width: 150,
	},
	{
		title: "验收单编号",
		dataIndex: "ys_code",
		sorter: false,
		width: 150,
	},
	{
		title: "验收人",
		dataIndex: "ys_user",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text?.fullname;
		}
	},
	// {
	// 	title: "核算分类",
	// 	dataIndex: "account_type_id",
	// 	sorter: false,
	// 	width: 150,
	// 	align: "center",
	// },
	// {
	// 	title: "使用部位",
	// 	dataIndex: "use_position",
	// 	sorter: false,
	// 	width: 200,
	// 	align: "center",
	// 	customRender: ({ text, record, index, column }) => {
	// 		return '';
	// 	}
	// },
	{
		title: "是否泵送（长度）",
		dataIndex: "changdu",
		sorter: false,
		width: 200,
		align: "center",
	},
	{
		title: "申请塌落度（mm）",
		dataIndex: "luodu",
		sorter: false,
		width: 200,
		align: "center",
	},
	{
		title: "预计浇筑部位",
		dataIndex: "expected_location",
		sorter: false,
		width: 200,
		align: "center",
	},
	// {
	// 	title: "支出方向",
	// 	dataIndex: "expenditure_id",
	// 	sorter: false,
	// 	width: 150,
	// 	align: "center",
	// },
	{
		title: "备注",
		dataIndex: "memo",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "附加价",
		dataIndex: "append_subprice",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "up_per",
		dataIndex: "up_per",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "综合含税单价\n(元)",
		dataIndex: "with_tax_subprice",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "含税总价\n(元)",
		dataIndex: "with_tax_amount",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "不含税单价\n(元)",
		dataIndex: "without_tax_subprice",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "不含税总价\n(元)",
		dataIndex: "without_tax_amount",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "税额\n(元)",
		dataIndex: "tax_amount",
		sorter: false,
		width: 150,
		align: "center",
	},
	{
		title: "税率",
		dataIndex: "tax",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return text ? text + '%' : '';
		}
	},
	{
		title: "品牌",
		dataIndex: "brand",
		sorter: false,
		width: 150,
		align: "center",
	},
];
const innerColumns = computed(() => {
	let columnList = columns;
	if (contract.value.price_type === 1 || !contract.value.price_type) {
		columnList = columnList.filter(item => item.title !== "up_per");
	}
	if (list.value[0]?.settlement.ys_type !== 2) {
		columnList = columnList.filter(item => !["expected_location", 'changdu', 'luodu'].includes(item.dataIndex));
	}
	return columnList;
});
const route = useRoute();
const contract_id = route.query.contract_id;
const optDisabled = ref(true);
const contract = ref({});
const loading = ref(false);
const list = ref([]);
const accountTypeOptions = ref([]);
const expenditureOptions = ref([]);
const gonghaoTree = ref([]);
const totalAmount = ref({
	append_subprice: 0,
	with_tax_amount: 0,
	with_tax_subprice: 0,
	without_tax_amount: 0,
	without_tax_subprice: 0,
	tax_amount: 0,
	amount: null,
});
const spinning = ref(false);
const formRef = ref();
const formOther = ref();
const applyArgs = ref({
	file_path: [],
	contract_name: '',
	supplier_name: '',
	memo: null,
	contract_file: null,
})
const { proxy } = getCurrentInstance();
const router = useRouter();
post("dictionary", { root_code: "ACCOUNT_TYPE" }).then(data => {
	accountTypeOptions.value = data || [];
});
post("dictionary", { root_code: "EXPENDITURE" }).then(data => {
	expenditureOptions.value = data;
});
onMounted(async () => {
	const result = await post(`settlement/material`, {
		settlement_id: route.params.id
	})
	const contractList = await post(`contract/all`, {
		contract_ids: result[0].contract_id,
	});
	contract.value = contractList[0];
	applyArgs.value.contract_name = contract.value.name;
	applyArgs.value.supplier_name = contract.value.supplier.company_name;
	applyArgs.value.contract_file = JSON.parse(contract.value.file_path)[0];
	applyArgs.value.memo = result[0]?.settlement.memo;
	// 商砼
	if ([1, 2, 3, 5].includes(result[0]?.settlement.ys_type)) {
		const usePositions = await post("department/getTrees", { type: 4, parent_id: contract.value.project_id });
		gonghaoTree.value = usePositions;
	}
	for (const item of result) {
		Object.assign(item, item.record);
		// 商砼
		if ([1, 2, 3, 5].includes(item?.settlement.ys_type)) {
			if (item.position || item.gonghao_id) {
				const gonghaoList = treeToList(JSON.parse(JSON.stringify(gonghaoTree.value)), []);
				const use_position = gonghaoList.filter((i) => {
					return i.id === (item.position || item.gonghao_id)
				})[0]
				item.use_position = use_position.value;
			}
		}
	}
	totalAmount.value.append_subprice = parseFloat(result[0].settlement.append_subprice);
	totalAmount.value.with_tax_amount = parseFloat(result[0].settlement.with_tax_amount);
	totalAmount.value.with_tax_subprice = parseFloat(result[0].settlement.with_tax_subprice);
	totalAmount.value.without_tax_amount = parseFloat(result[0].settlement.without_tax_amount);
	totalAmount.value.without_tax_subprice = parseFloat(result[0].settlement.without_tax_subprice);
	totalAmount.value.tax_amount = parseFloat(result[0].settlement.tax_amount);
	totalAmount.value.amount = parseFloat(result[0].settlement.amount);
	if (contract.value.price_type === 2) {
		totalAmount.value.up_per = parseFloat(result[0].settlement.up_per);
	}
	list.value = result;
})
const tableScroll = computed(() => ({ x: document.documentElement.clientWidth - 650 }));

// 改变部位
function changeUsePosition(record) {
	if (!record.use_position) {
		record.gonghao_id = null;
		record.position = null;
		return;
	}
	const gonghao_id = record.use_position.split('-')[1];
	let position = record.use_position.split('-').slice(-1)[0];
	if (gonghao_id === position) {
		position = null;
	}
	record.gonghao_id = gonghao_id;
	record.position = position;
}
// 提交
async function agree() {
	Modal.confirm({
		title: "操作确认?",
		content: "您确定通过结算吗，请确认",
		onOk() {
			spinning.value = true;
			post("settlement/audit", { id: route.params.id })
				.then(() => {
					spinning.value = false;
					proxy.$message.success("审核成功", 1);
					router.push('/settlement/history');
				})
				.catch(err => {
					proxy.$message.error(err);
					spinning.value = false;
				});
		}
	});
}
// 撤回
function revocation() {
	Modal.confirm({
		title: "操作确认?",
		content: "您确定撤销结算吗，请确认",
		onOk() {
			spinning.value = true;
			post("settlement/revocation", { id: route.params.id })
				.then(() => {
					spinning.value = false;
					proxy.$message.success("撤销成功", 1);
					router.push('/settlement');
				})
				.catch(err => {
					proxy.$message.error(err);
					spinning.value = false;
				});
		}
	});
}
// 返回
function back() {
	router.push('/settlement');
}
</script>
<style scoped lang="scss">
.container {
  background: #fff;
  padding: 12px;
}
:deep(.ant-table-cell) .ant-form-item {
  margin-bottom: 0;
}
:deep(.ant-descriptions-title) {
  text-align: center;
}
</style>
